import * as EventTypes from './EventTypes';
import { DeviceEventEmitter } from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation';
import AsyncStorage from '@react-native-community/async-storage';

export default class HomeEventHandler {
  constructor(view) {
    this.view = view;
    this.initHandlers();
  }

  initHandlers = () => {
    this.reloginEvent = DeviceEventEmitter.addListener(
      EventTypes.TOKEN_OUTDATE,
      this.reLogin
    );
    this.changeTabEvent = DeviceEventEmitter.addListener(
      EventTypes.CHANGE_TAB,
      this.changeTab
    );
    this.goStackPageEvent = DeviceEventEmitter.addListener(
      EventTypes.GO_STACK_PAGE,
      this.goStackPage
    );
  };

  //更改当前Tab
  changeTab = tabName => {
    this.view.props.navigation.navigate(tabName);
  };

  //根据跳转信息跳转到指定页面,并携带指定参数
  goStackPage = (pageName, params) => {
    console.log('接收到跳转信息 ==>', pageName, params);
    this.view.props.navigation.navigate(pageName, params);
  };

  reLogin = async () => {
    // Toast.info('您的登录信息已失效,请重新登录!');
    await AsyncStorage.setItem('Authorization', '');
    setTimeout(() => {
      const resetAction = StackActions.reset({
        index: 0,
        actions: [NavigationActions.navigate({ routeName: 'Login' })],
      });
      this.view.props.navigation.dispatch(resetAction);
    }, 2000);
  };

  removeHandlers = () => {
    this.reloginEvent.remove();
    this.changeTabEvent.remove();
    this.goStackPageEvent.remove();
  };
}
